package com.example.shuiyin.controller;

import com.example.shuiyin.dto.*;
import com.example.shuiyin.dto.ApiResponse;
import com.example.shuiyin.dto.AuthResponse;
import com.example.shuiyin.dto.BindPhoneRequest;
import com.example.shuiyin.dto.ForgotPasswordRequest;
import com.example.shuiyin.dto.RegisterRequest;
import com.example.shuiyin.dto.ResetPasswordRequest;
import com.example.shuiyin.dto.WxLoginRequest;
import com.example.shuiyin.dto.auth.*;
import com.example.shuiyin.entity.User;
import com.example.shuiyin.service.AuthService;
import com.example.shuiyin.service.UserService;
import com.example.shuiyin.service.AvatarService;
import com.example.shuiyin.service.MinioStorageService;
import com.example.shuiyin.exception.AppException;
import com.example.shuiyin.exception.ErrorCode;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {
    
    private final AuthService authService;
    private final UserService userService;
    private final AvatarService avatarService;
    private final MinioStorageService minioStorageService;
    
    @PostMapping("/wx-login")
    public ResponseEntity<ApiResponse<AuthResponse>> wxLogin(@Valid @RequestBody WxLoginRequest request) {
        AuthResponse response = authService.wxLogin(request);
        return ResponseEntity.ok(ApiResponse.success("微信登录成功", response));
    }
    
    @PostMapping("/bind-phone")
    public ResponseEntity<ApiResponse<AuthResponse>> bindPhone(@RequestAttribute("userId") Long userId, 
                                                 @Valid @RequestBody BindPhoneRequest request) {
        AuthResponse response = authService.bindPhone(userId, request);
        return ResponseEntity.ok(ApiResponse.success("手机绑定成功", response));
    }
    
    @PostMapping("/register")
    public ResponseEntity<ApiResponse<AuthResponse>> register(@Valid @RequestBody RegisterRequest request) {
        try {
            AuthResponse response = authService.register(request);
            return ResponseEntity.ok(ApiResponse.success("用户注册成功", response));
        } catch (Exception e) {
            // 由全局异常处理器处理异常
            throw e;
        }
    }
    
    @PostMapping("/login")
    public ResponseEntity<ApiResponse<AuthResponse>> login(@Valid @RequestBody LoginRequest request) {
        log.info("用户登录请求: {}", request.getUsername());
        
        // 输入验证 - 这部分由@Valid注解自动处理
        if (request.getUsername() == null || request.getUsername().trim().isEmpty() ||
            request.getPassword() == null || request.getPassword().trim().isEmpty()) {
            log.warn("登录失败: 用户名或密码为空");
            throw new AppException("用户名和密码不能为空", ErrorCode.INVALID_PARAMETER);
        }
        
        // 调用服务进行登录
        AuthResponse response = authService.login(request);
        log.info("用户[{}]登录成功", request.getUsername());
        return ResponseEntity.ok(ApiResponse.success("登录成功", response));
    }
    
    /**
     * 获取当前用户信息 (使用RequestAttribute的userId)
     */
    @GetMapping("/user")
    public ResponseEntity<ApiResponse<UserDto>> getCurrentUser(@RequestAttribute("userId") Long userId) {
        User user = authService.getUserById(userId);
        return ResponseEntity.ok(ApiResponse.success("获取用户信息成功", UserDto.fromEntity(user)));
    }
    
    /**
     * 获取所有用户列表
     */
    @PostMapping("/users/all")
    public ResponseEntity<ApiResponse<List<UserDto>>> getAllUsers(
            @RequestAttribute(value = "userId", required = false) Long userId,
            @RequestBody(required = false) Map<String, String> request) {
        
        // 验证当前用户是否有权限
        if (userId == null) {
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                .body(ApiResponse.error("未登录或登录已过期"));
    }
    
        // 获取当前用户，检查是否有管理员权限
        User currentUser = authService.getUserById(userId);
        if (currentUser == null || !"ADMIN".equals(currentUser.getRole())) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN)
                    .body(ApiResponse.error("没有权限访问该资源"));
        }

        // 获取所有用户
        List<User> users = userService.findAll();
        List<UserDto> userDtos = users.stream()
                .map(UserDto::fromEntity)
                .collect(Collectors.toList());

        return ResponseEntity.ok(ApiResponse.success("获取用户列表成功", userDtos));
    }
    
    /**
     * 获取当前用户信息 (POST方法)
     */
    @PostMapping("/user")
    public ResponseEntity<ApiResponse<UserDto>> getCurrentUserPost(
            @RequestAttribute(value = "userId", required = false) Long userId) {
        if (userId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(ApiResponse.error("未登录或登录已过期"));
        }
        
        User user = authService.getUserById(userId);
        if (user != null) {
            return ResponseEntity.ok(ApiResponse.success("获取用户信息成功", UserDto.fromEntity(user)));
        }
        
        return ResponseEntity.status(HttpStatus.NOT_FOUND)
                .body(ApiResponse.error("用户不存在"));
    }

    /**
     * 获取当前用户信息 (GET方法)
     */
    @GetMapping("/me")
    public ResponseEntity<ApiResponse<UserInfoResponse>> getCurrentUserInfo(
            @RequestAttribute(value = "userId", required = false) Long userId,
            @RequestHeader(value = "Authorization", required = false) String authHeader) {
        log.info("获取当前用户信息: userId={}, authHeader={}", userId, authHeader);
        
        // 如果请求属性中没有userId，尝试从Authorization header中获取token
        if (userId == null && StringUtils.hasText(authHeader) && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7);
                try {
                    if (authService.validateUserToken(token)) {
                        String tokenUserId = authService.getTokenProvider().getUserIdFromToken(token);
                        userId = Long.valueOf(tokenUserId);
                        log.info("从token中获取到用户ID: {}", userId);
                    }
                } catch (Exception e) {
                    log.warn("从token获取用户ID失败: {}", e.getMessage());
            }
        }
        
        // 如果仍然没有userId，返回空数据而不是错误
        if (userId == null) {
            return ResponseEntity.ok(ApiResponse.success("未登录用户", null));
        }
        
        try {
            User user = authService.getUserById(userId);
            if (user == null) {
                return ResponseEntity.ok(ApiResponse.success("用户不存在", null));
            }
            
            UserInfoResponse userInfo = new UserInfoResponse();
            userInfo.setId(user.getId());
            userInfo.setUsername(user.getUsername());
            userInfo.setNickname(user.getNickname());
            userInfo.setAvatarUrl(user.getAvatarUrl());
            userInfo.setRole(user.getRole());
            
        return ResponseEntity.ok(ApiResponse.success("获取用户信息成功", userInfo));
        } catch (Exception e) {
            log.error("获取用户信息异常", e);
            return ResponseEntity.ok(ApiResponse.error("获取用户信息失败: " + e.getMessage()));
        }
    }

    /**
     * 用户更新自己的信息
     */
    @PutMapping("/me")
    public ResponseEntity<ApiResponse<UserInfoResponse>> updateSelfInfo(
            @RequestBody UserUpdateRequest request,
            @RequestAttribute(value = "userId", required = false) Long currentUserId) {
        log.info("用户更新自己的信息: userId={}, request={}", currentUserId, request);
        
        try {
            if (currentUserId == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                        .body(ApiResponse.error("未登录或无法识别用户身份"));
            }
            
            // 不允许普通用户修改角色
            if (request.getRole() != null) {
                User currentUser = authService.getUserById(currentUserId);
                boolean isAdmin = currentUser != null && "ADMIN".equals(currentUser.getRole());
                if (!isAdmin) {
                    request.setRole(null); // 移除角色字段
                    log.warn("非管理员用户尝试修改自己的角色，已移除角色字段");
                }
            }
            
            // 调用service更新用户信息 - 使用当前用户ID
            UserInfoResponse updatedUser = authService.updateUserInfo(currentUserId, request);
            return ResponseEntity.ok(ApiResponse.success("更新个人信息成功", updatedUser));
        } catch (AppException e) {
            log.error("更新个人信息失败: {}", e.getMessage());
            return ResponseEntity
                .status(e.getStatusCode())
                .body(ApiResponse.error(
                    e.getCode(),
                    e.getMessage()
                ));
        } catch (Exception e) {
            log.error("更新个人信息出现未知错误", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error(
                        HttpStatus.INTERNAL_SERVER_ERROR.value(),
                        "更新个人信息失败: " + e.getMessage()
                    ));
        }
    }

    /**
     * 根据token更新用户信息
     */
    @PostMapping("/update")
    public ResponseEntity<ApiResponse<UserInfoResponse>> updateUserByToken(
            @RequestAttribute(value = "userId", required = false) Long userId,
            @RequestBody UserUpdateRequest request) {
        log.info("更新用户信息: userId={}, request={}", userId, request);
        
        try {
            if (userId == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                        .body(ApiResponse.error(ErrorCode.UNAUTHORIZED.getMessage()));
            }
            
            // 检查角色更新权限
            if (request.getRole() != null && !request.getRole().trim().isEmpty()) {
                if (!authService.isAdmin(userId)) {
                    request.setRole(null);
                    log.warn("非管理员用户尝试修改自己的角色，已忽略");
                }
            }
            
            UserInfoResponse updatedUser = authService.updateUserInfo(userId, request);
            return ResponseEntity.ok(ApiResponse.success("更新用户信息成功", updatedUser));
        } catch (AppException e) {
            log.error("更新用户信息失败: {}", e.getMessage());
            return ResponseEntity
                .status(e.getStatusCode())
                .body(ApiResponse.error(
                    e.getCode(),
                    e.getMessage()
                ));
        } catch (Exception e) {
            log.error("更新用户信息出现未知错误", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error(
                        HttpStatus.INTERNAL_SERVER_ERROR.value(),
                        "更新用户失败: " + e.getMessage()
                    ));
        }
    }

    /**
     * 管理员更新任意用户信息
     */
    @PutMapping("/admin/{id}")
    public ResponseEntity<ApiResponse<UserInfoResponse>> adminUpdateUserInfo(
            @PathVariable Long id,
            @RequestBody UserUpdateRequest request,
            @RequestAttribute(value = "userId", required = false) Long currentUserId) {
        log.info("管理员更新用户信息: targetId={}, request={}, adminId={}", id, request, currentUserId);
        
        try {
            if (currentUserId == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                        .body(ApiResponse.error(ErrorCode.UNAUTHORIZED.getMessage()));
            }
            
            // 验证管理员权限
            if (!authService.isAdmin(currentUserId)) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN)
                        .body(ApiResponse.error(ErrorCode.FORBIDDEN.getMessage()));
            }
            
            UserInfoResponse updatedUser = authService.updateUserInfo(id, request);
            return ResponseEntity.ok(ApiResponse.success("管理员更新用户信息成功", updatedUser));
        } catch (AppException e) {
            log.error("管理员更新用户信息失败: {}", e.getMessage());
            return ResponseEntity
                .status(e.getStatusCode())
                .body(ApiResponse.error(
                    e.getCode(),
                    e.getMessage()
                ));
        } catch (Exception e) {
            log.error("管理员更新用户信息出现未知错误", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error(
                        HttpStatus.INTERNAL_SERVER_ERROR.value(),
                        "管理员更新用户信息失败: " + e.getMessage()
                    ));
        }
    }
    
    /**
     * 上传头像（包含URL访问路径）
     */
    @PostMapping("/avatar")
    public ResponseEntity<ApiResponse<String>> uploadAvatar(
            @RequestParam("file") MultipartFile file,
            @RequestAttribute("userId") Long userId,
            HttpServletRequest request) {
        try {
            if (file.isEmpty()) {
                return ResponseEntity.badRequest()
                        .body(ApiResponse.error(6000, "请选择要上传的头像文件"));
            }
            
            // 验证文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return ResponseEntity.badRequest()
                        .body(ApiResponse.error(6001, "只支持上传图片格式的头像"));
            }
            
            // 获取文件扩展名
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            } else {
                // 根据内容类型确定扩展名
                if (contentType.equals("image/jpeg") || contentType.equals("image/jpg")) {
                    extension = ".jpg";
                } else if (contentType.equals("image/png")) {
                    extension = ".png";
                } else if (contentType.equals("image/gif")) {
                    extension = ".gif";
                } else {
                    extension = ".jpg"; // 默认
                }
            }
            
            // 生成文件名
            String filename = UUID.randomUUID().toString() + extension;
            
            // 上传到MinIO并获取URL
            String minioUrl = minioStorageService.uploadAvatar(file, userId, filename);
            
            // 获取当前服务器域名和端口，构建完整URL
            String serverBaseUrl = getServerBaseUrl(request);
            String avatarPath = "/api/avatar/" + userId + "/" + filename;
            String fullAvatarUrl = serverBaseUrl + avatarPath;
            
            // 更新用户头像信息
            User user = userService.findById(userId);
            if (user != null) {
                user.setAvatar(filename);
                user.setAvatarUrl(fullAvatarUrl); // 设置完整URL路径
                userService.updateUser(user);
                
                log.info("用户头像已更新 - 文件名: {}, URL: {}", filename, fullAvatarUrl);
            }
            
            // 返回完整的可访问URL
            return ResponseEntity.ok(ApiResponse.success("头像上传成功", fullAvatarUrl));
        } catch (Exception e) {
            log.error("上传头像失败: {}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error(5000, "上传头像失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取服务器基础URL
     */
    private String getServerBaseUrl(HttpServletRequest request) {
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        int serverPort = request.getServerPort();
        
        // 构建基础URL
        StringBuilder url = new StringBuilder();
        url.append(scheme).append("://").append(serverName);
        
        // 如果不是默认端口，添加端口号
        if ((scheme.equals("http") && serverPort != 80) || 
            (scheme.equals("https") && serverPort != 443)) {
            url.append(":").append(serverPort);
        }
        
        return url.toString();
    }

    // 简单的图片类型验证 (需要完善)
    private boolean isValidImageType(MultipartFile file) {
        String contentType = file.getContentType();
        return contentType != null && (contentType.equals("image/jpeg") || contentType.equals("image/png") || contentType.equals("image/gif"));
    }

    /**
     * 使用multipart/form-data更新用户信息
     */
    @PostMapping("/{id}/update")
    public ResponseEntity<ApiResponse<UserInfoResponse>> updateUserWithAvatar(
            @PathVariable Long id,
            @RequestParam(value = "nickname", required = false) String nickname,
            @RequestParam(value = "email", required = false) String email,
            @RequestParam(value = "phone", required = false) String phone,
            @RequestParam(value = "role", required = false) String role,
            @RequestParam(value = "avatar", required = false) MultipartFile avatar,
            @RequestAttribute(value = "userId", required = false) Long currentUserId) {
        
        log.info("更新用户信息(含头像): id={}, nickname={}, email={}, phone={}, role={}, 有头像={}, currentUserId={}",
                id, nickname, email, phone, role, avatar != null, currentUserId);
        
        try {
            // 验证权限
            Long authenticatedUserId = currentUserId;
            if (authenticatedUserId == null) {
                Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                if (principal instanceof User) {
                    authenticatedUserId = ((User) principal).getId();
                } else if (principal instanceof String) {
                    try {
                        authenticatedUserId = Long.parseLong((String) principal);
                    } catch (NumberFormatException e) {
                        log.warn("无法从principal获取用户ID: {}", principal);
                    }
                }
            }
            
            if (authenticatedUserId == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                        .body(ApiResponse.error(ErrorCode.UNAUTHORIZED.getMessage()));
            }
            
            // 只有自己或管理员可以修改用户信息
            User currentUser = authService.getUserById(authenticatedUserId);
            boolean isAdmin = currentUser != null && "ADMIN".equals(currentUser.getRole());
            boolean isSelf = authenticatedUserId.equals(id);
            
            if (!isAdmin && !isSelf) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN)
                        .body(ApiResponse.error(ErrorCode.FORBIDDEN.getMessage()));
            }
            
            // 准备更新请求
            UserUpdateRequest request = new UserUpdateRequest();
            request.setNickname(nickname);
            request.setEmail(email);
            request.setPhone(phone);
            
            // 只有管理员可以更新角色
            if (isAdmin) {
                request.setRole(role);
            } else if (role != null) {
                log.warn("非管理员尝试更新角色，已忽略");
            }
            
            // 处理头像上传
            if (avatar != null && !avatar.isEmpty()) {
                // 验证文件类型
                String contentType = avatar.getContentType();
                if (contentType == null || 
                        (!contentType.startsWith("image/jpeg") && 
                         !contentType.startsWith("image/png") && 
                         !contentType.startsWith("image/gif"))) {
                    return ResponseEntity.badRequest()
                            .body(ApiResponse.error(ErrorCode.INVALID_FILE_TYPE.getMessage()));
                }
                
                // 验证文件大小 (2MB)
                if (avatar.getSize() > 2 * 1024 * 1024) {
                    return ResponseEntity.badRequest()
                            .body(ApiResponse.error(ErrorCode.FILE_SIZE_EXCEEDED.getMessage()));
                }
                
                // 处理头像上传
                String originalFilename = avatar.getOriginalFilename();
                String uniqueFilename = UUID.randomUUID().toString() + "_" + originalFilename;
                
                String filePath = userService.saveAvatar(avatar, uniqueFilename, id);
                request.setAvatarUrl(filePath);
            }
            
            // 调用service更新用户信息
            UserInfoResponse updatedUser = authService.updateUserInfo(id, request);
            return ResponseEntity.ok(ApiResponse.success("更新用户信息成功", updatedUser));
            
        } catch (AppException e) {
            log.error("更新用户信息失败: {}", e.getMessage());
            return ResponseEntity
                .status(e.getStatusCode())
                .body(ApiResponse.error(
                    e.getCode(),
                    e.getMessage()
                ));
        } catch (Exception e) {
            log.error("更新用户信息失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error(
                        HttpStatus.INTERNAL_SERVER_ERROR.value(),
                        "更新用户失败: " + e.getMessage()
                    ));
        }
    }

    /**
     * 更新指定用户的信息
     */
    @PutMapping("/{userId}")
    public ResponseEntity<ApiResponse<UserInfoResponse>> updateUserInfo(
            @PathVariable Long userId,
            @RequestBody UserUpdateRequest request,
            @RequestAttribute(value = "userId", required = false) Long currentUserId) {
        log.info("更新用户信息: targetUserId={}, currentUserId={}, request={}", userId, currentUserId, request);
        
        try {
            if (currentUserId == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                        .body(ApiResponse.error(ErrorCode.UNAUTHORIZED.getMessage()));
            }
            
            // 检查权限
            User currentUser = authService.getUserById(currentUserId);
            boolean isAdmin = currentUser != null && "ADMIN".equals(currentUser.getRole());
            boolean isSelf = currentUserId.equals(userId);
            
            if (!isAdmin && !isSelf) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN)
                        .body(ApiResponse.error(ErrorCode.FORBIDDEN.getMessage()));
            }
            
            // 如果不是管理员，不允许修改角色
            if (!isAdmin && request.getRole() != null) {
                request.setRole(null);
                log.warn("非管理员用户尝试修改角色，已移除角色字段");
            }
            
            UserInfoResponse updatedUser = authService.updateUserInfo(userId, request);
            return ResponseEntity.ok(ApiResponse.success("更新用户信息成功", updatedUser));
        } catch (AppException e) {
            log.error("更新用户信息失败: {}", e.getMessage());
            return ResponseEntity
                .status(e.getStatusCode())
                .body(ApiResponse.error(
                    e.getCode(),
                    e.getMessage()
                ));
        } catch (Exception e) {
            log.error("更新用户信息出现未知错误", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error(
                        HttpStatus.INTERNAL_SERVER_ERROR.value(),
                        "更新用户失败: " + e.getMessage()
                    ));
        }
    }

    /**
     * 修改密码
     */
    @PostMapping("/password/change")
    public ResponseEntity<ApiResponse<Boolean>> changePassword(
            @RequestBody ChangePasswordRequest request,
            @RequestAttribute(value = "userId", required = false) Long userId) {
        log.info("用户修改密码: userId={}", userId);
        
        try {
            if (userId == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                        .body(ApiResponse.error(ErrorCode.UNAUTHORIZED.getMessage()));
            }
            
            boolean result = authService.changePassword(userId, request);
            return ResponseEntity.ok(ApiResponse.success("密码修改成功", result));
        } catch (AppException e) {
            log.error("修改密码失败: {}", e.getMessage());
            return ResponseEntity
                .status(e.getStatusCode())
                .body(ApiResponse.error(
                    e.getCode(),
                    e.getMessage()
                ));
        } catch (Exception e) {
            log.error("修改密码出现未知错误", e);
            return ResponseEntity
                .status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(ApiResponse.error(
                    HttpStatus.INTERNAL_SERVER_ERROR.value(),
                    "修改密码失败: " + e.getMessage()
                ));
        }
    }

    /**
     * 用户登出
     */
    @PostMapping("/logout")
    public ResponseEntity<ApiResponse<Void>> logout(
            @RequestAttribute(value = "userId", required = false) Long userId) {
        log.info("用户登出: userId={}", userId);
        
        try {
            // 由于使用JWT，服务端不需要特别的登出逻辑
            // 只需要客户端删除token即可
            return ResponseEntity.ok(ApiResponse.success("用户已成功登出"));
        } catch (Exception e) {
            log.error("用户登出失败: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error("登出失败: " + e.getMessage()));
        }
    }

    /**
     * 上传Base64编码的用户头像
     */
    @PostMapping("/avatar/base64")
    public ResponseEntity<ApiResponse<String>> uploadBase64Avatar(
            @RequestAttribute(value = "userId", required = false) Long currentUserId,
            @RequestBody Map<String, String> request) {
        
        String base64Image = request.get("image");
        Long id = null;
        if (request.containsKey("id")) {
            try {
                id = Long.parseLong(request.get("id"));
            } catch (NumberFormatException e) {
                return ResponseEntity.badRequest()
                        .body(ApiResponse.error("无效的用户ID"));
            }
        }
        
        Long targetUserId = id != null ? id : currentUserId;
        
        if (targetUserId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(ApiResponse.error(ErrorCode.UNAUTHORIZED.getMessage()));
        }
        
        // 权限检查
        if (!authService.isAdmin(currentUserId) && !targetUserId.equals(currentUserId)) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN)
                    .body(ApiResponse.error(ErrorCode.FORBIDDEN.getMessage()));
        }
        
        if (base64Image == null || base64Image.isEmpty()) {
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("Base64图片不能为空"));
        }
        
        try {
            // 处理Base64图片字符串
            String[] parts = base64Image.split(",");
            String imageData = parts.length > 1 ? parts[1] : parts[0];
            String contentType = "image/jpeg"; // 默认JPEG
            
            if (parts.length > 1 && parts[0].contains("image/")) {
                contentType = parts[0].substring(parts[0].indexOf(":") + 1, parts[0].indexOf(";"));
            }
            
            // 转换Base64为字节数组
            byte[] imageBytes = java.util.Base64.getDecoder().decode(imageData);
            
            // 创建MultipartFile
            MultipartFile multipartFile = new MockMultipartFile(
                    "file", 
                    "avatar.jpg", 
                    contentType, 
                    imageBytes
            );
            
            // 使用AvatarService上传头像
            String avatarUrl = avatarService.uploadAvatar(targetUserId, multipartFile);
            return ResponseEntity.ok(ApiResponse.success("头像上传成功", avatarUrl));
        } catch (AppException e) {
            log.error("上传头像业务异常: {}", e.getMessage());
            return ResponseEntity.status(e.getStatusCode())
                    .body(ApiResponse.error(e.getCode(), e.getMessage()));
        } catch (Exception e) {
            log.error("上传头像失败: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error(ErrorCode.FILE_UPLOAD_ERROR.getMessage()));
        }
    }

    /**
     * 删除账号
     */
    @DeleteMapping("/account")
    public ResponseEntity<ApiResponse<String>> deleteAccount(@RequestParam("userId") Long userId) {
        try {
            // 业务逻辑处理
            userService.deleteAccount(userId);
            
            return ResponseEntity.ok(ApiResponse.success("账号已成功删除", ""));
        } catch (Exception e) {
            log.error("删除账号失败: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error("删除账号失败: " + e.getMessage()));
        }
    }

    /**
     * 忘记密码 - 发送重置邮件
     */
    @PostMapping("/forgot-password")
    public ResponseEntity<ApiResponse<Boolean>> forgotPassword(@Valid @RequestBody ForgotPasswordRequest request) {
        log.info("忘记密码请求: {}", request.getEmail());
        try {
            authService.sendPasswordResetEmail(request.getEmail());
            
            // 无论用户是否存在，都返回成功，避免泄露用户信息
            return ResponseEntity.ok(ApiResponse.success("密码重置链接已发送到您的邮箱", true));
        } catch (Exception e) {
            log.error("发送密码重置邮件失败: {}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error("发送密码重置邮件失败: " + e.getMessage()));
        }
    }

    /**
     * 重置密码
     */
    @PostMapping("/reset-password")
    public ResponseEntity<ApiResponse<Boolean>> resetPassword(@Valid @RequestBody ResetPasswordRequest request) {
        log.info("重置密码请求: token={}", request.getToken());
        try {
            authService.resetPassword(request.getToken(), request.getPassword());
            return ResponseEntity.ok(ApiResponse.success("密码已成功重置", true));
        } catch (AppException e) {
            log.error("重置密码失败: {}", e.getMessage());
            return ResponseEntity.status(e.getStatusCode())
                    .body(ApiResponse.error(e.getCode(), e.getMessage()));
        } catch (Exception e) {
            log.error("重置密码失败: {}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error("重置密码失败: " + e.getMessage()));
        }
    }

    @PostMapping("/test-register")
    public ResponseEntity<ApiResponse<AuthResponse>> testRegister(@Valid @RequestBody RegisterRequest request) {
        try {
            // 查验用户名和邮箱是否已存在
            User user = userService.findByUsername(request.getUsername());
            if (user != null) {
                return ResponseEntity.badRequest()
                    .body(ApiResponse.error(1001, "用户名已存在"));
            }
            
            user = userService.findByEmail(request.getEmail());
            if (user != null) {
                return ResponseEntity.badRequest()
                    .body(ApiResponse.error(1002, "邮箱已被使用"));
            }
            
            // 创建用户 - 密码使用固定值便于测试
            User newUser = new User();
            newUser.setUsername(request.getUsername());
            newUser.setEmail(request.getEmail());
            // 使用固定值作为密码，便于测试
            newUser.setPassword("$2a$10$w5LaoAEwR75C0VzTQ50fceM85hh4AprgYmtbfrECXw2kYoFcAup7K"); 
            newUser.setRole("USER");
            newUser.setSalt(UUID.randomUUID().toString());
            newUser.setUserLevel(1);
            newUser.setStatus("ACTIVE");
            newUser.setCreatedAt(LocalDateTime.now());
            newUser.setUpdatedAt(LocalDateTime.now());
            
            userService.save(newUser);
            
            // 生成JWT令牌
            String token = authService.getTokenProvider().generateToken(newUser.getId().toString());
            
            return ResponseEntity.ok(ApiResponse.success("测试用户创建成功，固定密码为12345678", 
                AuthResponse.builder()
                    .token(token)
                    .username(newUser.getUsername())
                    .email(newUser.getEmail())
                    .isNewUser(true)
                    .build()));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(ApiResponse.error("测试用户创建失败: " + e.getMessage()));
        }
    }

    /**
     * 管理员重置用户密码 - 用于修复密码哈希问题
     */
    @PostMapping("/admin/reset-user-password")
    public ResponseEntity<ApiResponse<Boolean>> adminResetUserPassword(
            @RequestAttribute("userId") Long adminUserId,
            @RequestBody Map<String, Object> request) {
            
        // 验证管理员权限
        if (!authService.isAdmin(adminUserId)) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN)
                    .body(ApiResponse.error(4001, "没有管理员权限"));
        }
        
        // 提取参数
        Long targetUserId = null;
        String newPassword = null;
        
        try {
            targetUserId = Long.valueOf(request.get("userId").toString());
            newPassword = request.get("password").toString();
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error(6001, "无效的参数格式"));
        }
        
        // 参数验证
        if (targetUserId == null || newPassword == null || newPassword.length() < 6) {
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error(6000, "用户ID不能为空且密码长度至少为6位"));
        }
        
        try {
            // 执行密码重置
            boolean result = authService.adminResetUserPassword(targetUserId, newPassword);
            if (result) {
                return ResponseEntity.ok(ApiResponse.success("密码重置成功", true));
            } else {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                        .body(ApiResponse.error(1000, "密码重置失败"));
            }
        } catch (AppException e) {
            return ResponseEntity.status(e.getHttpStatus())
                    .body(ApiResponse.error(e.getCode(), e.getMessage()));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error(500, "系统错误: " + e.getMessage()));
        }
    }

    /**
     * 临时紧急登录接口 - 仅用于解决当前登录问题
     */
    @PostMapping("/emergency-login")
    public ResponseEntity<ApiResponse<AuthResponse>> emergencyLogin(@RequestBody Map<String, String> request) {
        try {
            String username = request.get("username");
            
            if (username == null || username.isEmpty()) {
                return ResponseEntity.badRequest()
                        .body(ApiResponse.error(1001, "用户名不能为空"));
            }
            
            // 查找用户
            User user = userService.findByUsername(username);
            if (user == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                        .body(ApiResponse.error(1007, "用户不存在"));
            }
            
            // 生成JWT令牌，跳过密码验证
            String token = authService.getTokenProvider().generateToken(user.getId().toString());
            
            // 返回登录成功响应
            AuthResponse response = AuthResponse.builder()
                    .token(token)
                    .username(user.getUsername())
                    .email(user.getEmail())
                    .phone(user.getPhone())
                    .avatarUrl(user.getAvatarUrl())
                    .isNewUser(false)
                    .build();
                    
            return ResponseEntity.ok(ApiResponse.success("紧急登录成功", response));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error(500, "登录失败: " + e.getMessage()));
        }
    }
    
    /**
     * 紧急重置密码 - 无需验证原密码，仅用于解决当前问题
     */
    @PostMapping("/emergency-reset-password")
    public ResponseEntity<ApiResponse<User>> emergencyResetPassword(@RequestBody Map<String, String> request) {
        try {
            String username = request.get("username");
            String newPassword = request.get("newPassword");
            
            if (username == null || username.isEmpty() || newPassword == null || newPassword.isEmpty()) {
                return ResponseEntity.badRequest()
                        .body(ApiResponse.error(1001, "用户名和新密码不能为空"));
            }
            
            // 查找用户
            User user = userService.findByUsername(username);
            if (user == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(ApiResponse.error(1007, "用户不存在"));
            }
            
            // 直接更新密码，使用标准BCrypt
            PasswordEncoder encoder = new BCryptPasswordEncoder(10);
            user.setPassword(encoder.encode(newPassword));
            user.setUpdatedAt(LocalDateTime.now());
            
            userService.save(user);
            
            // 清除敏感信息
            user.setPassword("[PROTECTED]");
            
            return ResponseEntity.ok(ApiResponse.success("密码重置成功", user));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error(500, "密码重置失败: " + e.getMessage()));
        }
    }
} 